package services.lmpl;

import entity.Customer;
import entity.Order;
import entity.Products;
import entity.Supplier;
import services.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Vector;

public class Servicelmpl implements Service {
    Map<String,Products> productMap = new HashMap<String,Products>();
    Map<String ,Supplier> supplierMap = new HashMap<String,Supplier>();
    Map<String, Customer> customerMap = new HashMap<String, Customer>();
    Map<String, Order> orderMap = new HashMap<String, Order>();
    public Servicelmpl() {
       loadInfo();
    }
    @Override
    public Map<String, Products> getProductMap() {
        return productMap;
    }
    @Override
    public Map<String, Supplier> getSupplierMap() {
        return supplierMap;
    }
    @Override
    public Map<String, Customer> getCustomerMap() {
        return customerMap;
    }
    @Override
    public Map<String, Order> getOrderMap() {
        return orderMap;
    }
    @Override
    public void close() throws FileNotFoundException {
        PrintWriter output;
        output = new PrintWriter("information/products.csv");
        for(Products products : productMap.values()){
            output.println(products.getId()+","+products.getName()+","+products.getSuppliperId()+","+products.getInventory()+","+
                    products.getCost()+","+products.getPrice()+","+((new SimpleDateFormat("yy-MM-dd")).format(products.getJoinData())));
        }
        output.close();
        System.out.println("close products.csv");
        output = new PrintWriter("information/supplier.csv");
        if(supplierMap!= null) {
            for (Supplier supplier : supplierMap.values()) {
                StringBuilder productsIds = new StringBuilder();
                if (supplier.getProductsid().size() > 0) {
                    productsIds.append(supplier.getProductsid().get(0));
                }
                for (int i = 1; i < supplier.getProductsid().size(); i++) {
                    productsIds.append("=").append(supplier.getProductsid().get(i));
                }
                output.println(supplier.getId() + "," + supplier.getName() + "," + supplier.getTel() + "," + supplier.getMail() + "," + supplier.getAddr() + "," +
                        ((new SimpleDateFormat("yy-MM-dd")).format(supplier.getJoinDate())) + "," + productsIds + "," + supplier.getDelFlag());
            }
        }
        output.close();
        System.out.println("closed supplier.csv");
        output = new PrintWriter("information/customer.csv");
        for (Customer customer:customerMap.values()){
            StringBuilder productsIds = new StringBuilder();
            if(customer.getProductsid().size()>0){
                productsIds.append(customer.getProductsid().get(0));
            }
            for (int i =1; i < customer.getProductsid().size();i++){
                productsIds.append("=").append(customer.getProductsid().get(i));
            }
            output.println(customer.getId()+","+customer.getName()+","+customer.getTel()+","+customer.getMail()+","+
                    customer.getAddr()+","+((new SimpleDateFormat("yy-MM-dd")).format(customer.getJoinDate()))+","+productsIds+","+customer.getDelFlag());
        }
        output.close();
        System.out.println("closed customer.csv");
        output = new PrintWriter("information/order.csv");
        for (Order order:orderMap.values()){
            StringBuilder productsIds = new StringBuilder();
            StringBuilder amounts = new StringBuilder();
            if(order.getProductsIds().size()>0 && order.getAmounts().size()>0){
                order.getProductsIds().get(0);
                productsIds.append(order.getProductsIds().get(0));
                amounts.append(order.getAmounts().get(0));
            }
            for (int i =1; i < order.getProductsIds().size();i++){
                productsIds.append("=").append(order.getProductsIds().get(i));
            }
            for (int i =1; i < order.getAmounts().size();i++){
                amounts.append("=").append(order.getAmounts().get(i));
            } //Order:订单编号,客户名称,商品名称[],数量[],成交日期
            output.println(order.getId()+","+order.getCustomerId()+","+productsIds+","+amounts+","+order.getPrice()+","+
                    ((new SimpleDateFormat("yy-MM-dd")).format(order.getTransactionDate())));
        }
        output.close();
        System.out.println("closed order.csv");
    }

    // 从文件中加载信息
    private void loadInfo(){
        BufferedReader productsBufferedReader= null;
        BufferedReader supplierBufferedReader= null;
        BufferedReader customerBufferedReader= null;
        BufferedReader orderBufferedReader= null;
        try {
            productsBufferedReader=new BufferedReader(new FileReader(new File("information/products.csv")));
            supplierBufferedReader=new BufferedReader(new FileReader(new File("information/supplier.csv")));
            customerBufferedReader=new BufferedReader(new FileReader(new File("information/customer.csv")));
            orderBufferedReader=new BufferedReader(new FileReader(new File("information/order.csv")));
            String line;
            try { // Product:名称,供应商名称,库存,成本,售价,入库时间
                while((line=productsBufferedReader.readLine())!=null) {
                    String[] strs=line.split(",");
                    if(strs.length>5){
                        Products p = new Products(strs[0], strs[1],strs[2], Integer.parseInt(strs[3]), Double.parseDouble(strs[4]),
                                Double.parseDouble(strs[5]), (new SimpleDateFormat("yy-MM-dd")).parse(strs[6])
                        );
                        productMap.put(strs[0],p);
                    }
                }
                // Personnel/Supplier/Customer:名字,电话,邮箱,地址,录入时间,关联的[],是否被删除
                while((line=supplierBufferedReader.readLine())!=null) {
                    String[] strs=line.split(",");
                    if(strs.length>5){
                        String[] productsIds = strs[6].split("=");
                        ArrayList<String> productsNameArrayList = new ArrayList<String>(Arrays.asList(productsIds));
                        Supplier s = new Supplier(strs[0], strs[1], strs[2], strs[3],strs[4], (new SimpleDateFormat("yy-MM-dd")).parse(strs[5]),
                                productsNameArrayList, Integer.parseInt(strs[7]));
                        supplierMap.put(strs[0],s);
                    }
                }
                while((line=customerBufferedReader.readLine())!=null) {
                    String[] strs=line.split(",");
                    if(strs.length>5){
                        String[] productsIds = strs[6].split("=");
                        ArrayList<String> orderIdsArrayList = new ArrayList<String>(Arrays.asList(productsIds));
                        Customer c = new Customer(strs[0], strs[1], strs[2], strs[3],strs[4],
                                (new SimpleDateFormat("yy-MM-dd")).parse(strs[5]), orderIdsArrayList, Integer.parseInt(strs[7])
                        );
                        customerMap.put(strs[0],c);
                    }
                }
                //Order:订单编号,客户名称,商品名称[],数量[],成交日期
                while((line=orderBufferedReader.readLine())!=null) {
                    String[] strs=line.split(",");

                    if(strs.length>4){
                        String[] productNames = strs[2].split("=");
                        String[] amounts = strs[3].split("=");
                        ArrayList<String> productArrayList = new ArrayList<String>(Arrays.asList(productNames));
                        ArrayList<Integer> amounrtArrayList = new ArrayList<Integer>();
                        for(String a : amounts ){
                            if(a.length()>0){
                                amounrtArrayList.add(Integer.parseInt(a));
                            }
                        }
                        Order o = new Order(strs[0], strs[1], productArrayList, amounrtArrayList, Double.parseDouble(strs[4]),
                                (new SimpleDateFormat("yy-MM-dd")).parse(strs[5]));
                        orderMap.put(strs[0],o);
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    // which -> 0:Products, 1:Supplier, 2:Customer, 3:Order
    // 新添
    @Override
    public int insertById(int which, Object object) throws Exception {
        switch (which){
            case 0:
                Products p = (Products) object;
                productMap.put(p.getId(),p);
                supplierMap.get(p.getSuppliperId()).insert(p.getId());
                break;
            case 1:
                Supplier s = (Supplier) object;
                supplierMap.put(s.getId(),s);
                break;
            case 2:
                Customer c = (Customer) object;
                customerMap.put(c.getId(),c);
                break;
            case 3:
                Order o = (Order) object;
                orderMap.put(o.getId(),o);
                customerMap.get(o.getCustomerId()).insert(o.getId());
                break;
            default:
                return 0;
        }
        return 1;
    }

    // 根据id删除
    @Override
    public int deleteById(int which, String id) throws Exception {
        switch (which){
            case 0:
                supplierMap.remove(productMap.get(id).getSuppliperId()).delete(id);
                productMap.remove(id);
                break;
            case 1:
                supplierMap.get(id).setDelFlag(1);
                break;
            case 2:
                customerMap.get(id).setDelFlag(1);
                break;
            case 3:
                customerMap.get(orderMap.get(id).getCustomerId()).delete(id);
                orderMap.remove(id);
                break;
            default:
                return 0;
        }
        return 1;
    }

    // 更新某一条信息
    @Override
    public int update(int which, Object object) throws Exception {
        System.out.println("update->"+which+","+object);
        switch (which){
            case 0:
                Products products = (Products) object;//编号,名称,供应商编码,库存,成本,售价,入库时间
                Products oldProducts = productMap.get(products.getId());
                oldProducts.setName(products.getName());
                oldProducts.setSuppliperId(products.getSuppliperId());
                oldProducts.setInventory(products.getInventory());
                oldProducts.setCost(products.getCost());
                oldProducts.setPrice(products.getPrice());
                oldProducts.setJoinData(products.getJoinData());
                if(!Objects.equals(oldProducts.getSuppliperId(), products.getSuppliperId())){
                    supplierMap.get(oldProducts.getSuppliperId()).getProductsid().remove(oldProducts.getId());
                    supplierMap.get(products.getSuppliperId()).getProductsid().add(products.getId());
                }
                break;
            case 1:
                Supplier supplier = (Supplier) object;
                Supplier oldSuppliper = supplierMap.get(supplier.getId());//名字,电话,邮箱,地址,录入时间
                oldSuppliper.setName(supplier.getName());
                oldSuppliper.setTel(supplier.getTel());
                oldSuppliper.setMail(supplier.getMail());
                oldSuppliper.setAddr(supplier.getAddr());
                oldSuppliper.setJoinDate(supplier.getJoinDate());
                break;
            case 2:
                Customer customer = (Customer) object;
                Customer oldCustomer = customerMap.get(customer.getId());
                oldCustomer.setName(customer.getName());
                oldCustomer.setTel(customer.getTel());
                oldCustomer.setMail(customer.getMail());
                oldCustomer.setAddr(customer.getAddr());
                oldCustomer.setJoinDate(customer.getJoinDate());
                break;
            case 3:
                Order order = (Order) object;  //订单编号,客户编号,商品编号[],数量[],成交日期
                Order oldOrder = orderMap.get(order.getId());
                oldOrder.setCustomerId(order.getCustomerId());
                oldOrder.setProductsIds(order.getProductsIds());
                oldOrder.setAmounts(order.getAmounts());
                oldOrder.setTransactionDate(order.getTransactionDate());
                break;
            default:
                return 0;
        }
        return 1;
    }

    // 根据id查询
    @Override
    public List selectById(int which, String id) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        switch (which){
            case 0:
                Products products = productMap.get(id);
                list.add(products.getId());
                list.add(products.getName());
                list.add((String) selectById(1,products.getSuppliperId()).get(1));
                list.add(""+products.getInventory());
                list.add(""+products.getCost());
                list.add(""+products.getPrice());
                list.add((new SimpleDateFormat("yy-MM-dd")).format(products.getJoinData()));
                break;
            case 1:
                Supplier supplier = supplierMap.get(id);
                list.add(supplier.getId());
                list.add(supplier.getName());
                list.add(supplier.getTel());
                list.add(supplier.getMail());
                list.add(supplier.getAddr());
                list.add((new SimpleDateFormat("yy-MM-dd")).format(supplier.getJoinDate()));
                break;
            case 2:
                Customer customer = customerMap.get(id);
                list.add(customer.getId());
                list.add(customer.getName());
                list.add(customer.getTel());
                list.add(customer.getMail());
                list.add(customer.getAddr());
                list.add((new SimpleDateFormat("yy-MM-dd")).format(customer.getJoinDate()));
                break;
            case 3:
                Order order = orderMap.get(id);
                list.add(order.getId());
                list.add(customerMap.get(order.getCustomerId()).getName());
                int sum = 0;
                for(int amunt : order.getAmounts()){
                    sum += amunt;
                }
                list.add(""+sum);
                list.add(""+order.getPrice());
                list.add((new SimpleDateFormat("yy-MM-dd")).format(order.getTransactionDate()));
                break;
            default:
                return null;
        }
        return list;
    }

    @Override
    public Vector<Vector> selectVectorById(int which, String id) throws Exception {
        Vector<Vector> rows = new Vector<Vector>();
        Vector<String> colum = null;
        switch (which){
            case 0:
                Products products = productMap.get(id);
                if(products!=null) {
                    colum = new Vector<String>();
                    colum.add(products.getId());
                    colum.add(products.getName());
                    colum.add((String) selectById(1, products.getSuppliperId()).get(1));
                    colum.add("" + products.getInventory());
                    colum.add("" + products.getCost());
                    colum.add("" + products.getPrice());
                    colum.add((new SimpleDateFormat("yy-MM-dd")).format(products.getJoinData()));
                    rows.add(colum);
                }
                break;
            case 1:
                Supplier supplier = supplierMap.get(id);
                if(supplier!= null) {
                    colum = new Vector<String>();
                    colum.add(supplier.getId());
                    colum.add(supplier.getName());
                    colum.add(supplier.getTel());
                    colum.add(supplier.getMail());
                    colum.add(supplier.getAddr());
                    colum.add((new SimpleDateFormat("yy-MM-dd")).format(supplier.getJoinDate()));
                    rows.add(colum);
                }
                break;
            case 2:
                Customer customer = customerMap.get(id);
                if(customer!=null) {
                    colum = new Vector<String>();
                    colum.add(customer.getId());
                    colum.add(customer.getName());
                    colum.add(customer.getTel());
                    colum.add(customer.getMail());
                    colum.add(customer.getAddr());
                    colum.add((new SimpleDateFormat("yy-MM-dd")).format(customer.getJoinDate()));
                    rows.add(colum);
                }
                break;
            case 3:
                Order order = orderMap.get(id);
                if(order!=null) {
                    colum.add(order.getId());
                    colum.add((String) selectById(2, order.getCustomerId()).get(1));
                    int sum = 0;
                    for (int amunt : order.getAmounts()) {
                        sum += amunt;
                    }
                    colum.add("" + sum);
                    colum.add("" + order.getPrice());
                    colum.add((new SimpleDateFormat("yy-MM-dd")).format(order.getTransactionDate()));
                }
                break;

            default:
                return null;
        }
        return rows;
    }
    // 通过名字查询
    @Override
    public Vector<Vector> selectByName(int which, String name) throws Exception {
        Vector<Vector> rows = new Vector<Vector>();
        Vector<String> colum = null;
        switch (which){
            case 0:
                for(Products products : productMap.values()){
                    if (products.getName().contains(name)) {
                        colum = new Vector<String>();
                        colum.add(products.getId());
                        colum.add(products.getName());
                        colum.add((String) selectById(1,products.getSuppliperId()).get(1));
                        colum.add(""+products.getInventory());
                        colum.add(""+products.getCost());
                        colum.add(""+products.getPrice());
                        colum.add((new SimpleDateFormat("yy-MM-dd")).format(products.getJoinData()));
                        rows.add(colum);
                    }
                }
                break;
            case 1:
                for (Supplier supplier:supplierMap.values()){
                    if (supplier.getDelFlag() == 0 && supplier.getName().contains(name)) {
                        colum = new Vector<String>();
                        colum.add(supplier.getId());
                        colum.add(supplier.getName());
                        colum.add(supplier.getTel());
                        colum.add(supplier.getMail());
                        colum.add(supplier.getAddr());
                        colum.add((new SimpleDateFormat("yy-MM-dd")).format(supplier.getJoinDate()));
                        rows.add(colum);
                    }
                }
                break;
            case 2:
                for (Customer customer:customerMap.values()){
                    if(customer.getDelFlag() == 0 && customer.getName().contains(name)) {
                        colum = new Vector<String>();
                        colum.add(customer.getId());
                        colum.add(customer.getName());
                        colum.add(customer.getTel());
                        colum.add(customer.getMail());
                        colum.add(customer.getAddr());
                        colum.add((new SimpleDateFormat("yy-MM-dd")).format(customer.getJoinDate()));
                        rows.add(colum);
                    }
                }
                break;
            case 3:
                for (Order order:orderMap.values()){
                    if((customerMap.get(order.getCustomerId())).getName().contains(name)){
                        colum = new Vector<String>();
                        colum.add(order.getId());
                        colum.add((String) selectById(2,order.getCustomerId()).get(1));
                        int sum = 0;
                        for(int amunt : order.getAmounts()){
                            sum += amunt;
                        }
                        colum.add(""+sum);
                        colum.add(""+order.getPrice());
                        colum.add((new SimpleDateFormat("yy-MM-dd")).format(order.getTransactionDate()));
                        rows.add(colum);
                    }
                }
                break;
            default:
        }
        return rows;
    }
    @Override
    public Vector<Vector> selectByIds(int which, ArrayList<String> ids , ArrayList<Integer> amounts) throws Exception {
        Vector<Vector> rows = new Vector<Vector>();
        Vector<String> colum = null;
        int i = 0;
        for(String id :ids){
            colum = new Vector<String>();
            for(Vector s : selectVectorById(which,id)){
                colum.addAll(s);
                colum.add(""+ amounts.get(i));
                i++;
            }

            rows.add(colum);

        }
        return rows;
    }
    // 获取所有信息
    @Override
    public Vector<Vector> selectAllVexctor(int which) throws Exception {
        Vector<Vector> rows = new Vector<Vector>();
        Vector<String> colum = null;
        switch (which){
            case 0:
                for(Products products : productMap.values()){
                    colum = new Vector<String>();
                    colum.add(products.getId());
                    colum.add(products.getName());
                    colum.add((String) selectById(1,products.getSuppliperId()).get(1));
                    colum.add(""+products.getInventory());
                    colum.add(""+products.getCost());
                    colum.add(""+products.getPrice());
                    colum.add((new SimpleDateFormat("yy-MM-dd")).format(products.getJoinData()));
                    rows.add(colum);
                }
                break;
            case 1:
                for (Supplier supplier:supplierMap.values()){
                    if (supplier.getDelFlag() == 0) {
                        colum = new Vector<String>();
                        colum.add(supplier.getId());
                        colum.add(supplier.getName());
                        colum.add(supplier.getTel());
                        colum.add(supplier.getMail());
                        colum.add(supplier.getAddr());
                        colum.add((new SimpleDateFormat("yy-MM-dd")).format(supplier.getJoinDate()));
                        rows.add(colum);
                    }
                }
                break;
            case 2:
                for (Customer customer:customerMap.values()){
                    if(customer.getDelFlag() == 0) {
                        colum = new Vector<String>();
                        colum.add(customer.getId());
                        colum.add(customer.getName());
                        colum.add(customer.getTel());
                        colum.add(customer.getMail());
                        colum.add(customer.getAddr());
                        colum.add((new SimpleDateFormat("yy-MM-dd")).format(customer.getJoinDate()));
                        rows.add(colum);
                    }
                }
                break;
            case 3:
                for (Order order:orderMap.values()){
                    colum = new Vector<String>();
                    colum.add(order.getId());
                    colum.add((String) selectById(2,order.getCustomerId()).get(1));
                    int sum = 0;
                    for(int amunt : order.getAmounts()){
                        sum += amunt;
                    }
                    colum.add(""+sum);
                    colum.add(""+order.getPrice());
                    colum.add((new SimpleDateFormat("yy-MM-dd")).format(order.getTransactionDate()));
                    rows.add(colum);
                }
                break;
            default:
                return null;
        }
        return rows;
    }


    @Override
    public Vector<Vector> selectProductsbyOrder(String id) throws Exception {
        Vector<Vector> rows = new Vector<Vector>();
        Vector<String> colum = null;
        boolean flag = false;
        for (Order order1:orderMap.values()){
            if(order1.getId().equals(id)){
                flag = true;
                ArrayList<String> productsIds = order1.getProductsIds();
                for(String productsId : productsIds){
                    colum = (Vector<String>) selectById(0,productsId);
                    rows.add(colum);
                }
                break;
            }
        }
        if(flag){
            return null;
        }
        return rows;
    }
    @Override
    public Map<String,String> selectAllIdName(int which){
        Map<String,String> maps = new HashMap<String, String>();
        switch (which){
            case 0:
                for(Products products : productMap.values()){
                    maps.put(products.getName(),products.getId());
                }
                break;
            case 1:
                for (Supplier supplier:supplierMap.values()){
                    if (supplier.getDelFlag() == 0) {
                        maps.put(supplier.getName(), supplier.getId());
                    }
                }
                break;
            case 2:
                for (Customer customer:customerMap.values()){
                    if(customer.getDelFlag() == 0) {
                        maps.put(customer.getName(), customer.getId());
                    }
                }
                break;
            case 3:
            default:
                return null;
        }
        return maps;
    }
}
